import type http from 'http'
import formidable, { errors as formidableErrors } from 'formidable';
import { app, BrowserWindow, shell, ipcMain, Menu } from 'electron'
import fs from 'node:fs'
import { doOCR } from '../libs/ocrsdk';


const form = formidable({
  multiples: false,
  maxFieldsSize: 1024 * 1024 * 10,
  encoding: 'utf-8',
  maxFields: 100000
});

/**
 * 接收APP端发过来的ocr结果
 */
export async function getMobileCameraImage(
  req: http.IncomingMessage,
  res: http.ServerResponse<http.IncomingMessage>
) {

  let [fields, files] = await form.parse(req);

  if (!files || !files.img || !files.img[0]) {
    res.end(JSON.stringify({ code: 500, message: "请上传图片" }));
    return;
  }

  if (files.img[0].mimetype != "image/jpeg" && files.img[0].mimetype != "image/jpg" && files.img[0].mimetype != "image/png") {
    res.end(JSON.stringify({ code: 500, message: "暂不支持此文件类型" }));
    return;
  }

  const imgTempPath = files.img[0].filepath;

  // 返回响应成功
  res.end(JSON.stringify({ code: 200, message: "success" }));


  fs.readFile(imgTempPath, (err: any, data: any) => {

    if (err) {
      console.log("图片读取出错！", err);
      return;
    }

    const imgBase64 = Buffer.from(data).toString('base64');


    doOCR(imgBase64).then((result) => {




      // console.log("res 识别的结果", res);
    }).catch((err) => {
      console.log("err", err);
    })


    res.end("success")

  })
}


